package com.example.gobang;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobRealTimeData;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.ValueEventListener;

public class MyWuZiQi extends View {
    private static final String INSTANCE = "instance";
    private static final String INSTANCE_GAME_OVER = "instance_game_over";
    private static final String INSTANCE_WHITE_ARRAY = "instance_white_array";
    private static final String INSTANCE_BLACK_ARRAY = "instance_black_array";
    private int mPanelWidth;
    private float mLineHeight;
    private int MAX_LINE = 10;
    private Paint paint = new Paint();
    private Bitmap whitepiece;
    private Bitmap blackpiece;
    private float ratioPieceOfLineHeight = 3 * 1.0f / 4;
    private boolean isWhite = true;
    private ArrayList<Point> whiteArray = new ArrayList<>();
    private ArrayList<Point> blackArray = new ArrayList<>();
    private boolean isGameOver;
    private boolean isWhiteWinner;
    private int MAX_COUNT_IN_LINE = 5;
    private int TYPE = 0;
    private String whiteJson = "";
    private String blackJson = "";
    private Handler handler;
    private String objID;
    private boolean CurIsWhite;
    private boolean canGo = false;
    private BmobRealTimeData rtd =new BmobRealTimeData();

    public MyWuZiQi(Context context) {
        super(context);
    }

    public MyWuZiQi(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public MyWuZiQi(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        Bmob.initialize(getContext(), "1e2264f8ca359778399a79719c56d8f5");
        setBackgroundColor(0x44ff0000);
        initPaint();
        initHandler();
        initRTD();

    }

    private void initRTD() {
        rtd.start(new ValueEventListener() {
            @Override
            public void onConnectCompleted(Exception e) {
                if (rtd.isConnected()){
                    rtd.subRowUpdate("GoBang",objID);
                }
            }

            @Override
            public void onDataChange(JSONObject jsonObject) {
                Message message=new Message();
                message.what=1111;
                handler.sendMessage(message);
            }
        });
    }

    public void setCanGo(boolean canGo) {
        this.canGo = canGo;
    }

    public void setCurIsWhite(boolean curIsWhite) {
        CurIsWhite = curIsWhite;
    }

    private void initHandler() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if (message.what == 1) {
                    isWhite = !isWhite;
                    return true;
                }else if (message.what==1111){
                    Log.e("data","dataChange");
                }
                return false;
            }
        });
    }

    private void initPaint() {
        paint.setColor(0x88000000);
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setStyle(Paint.Style.STROKE);
        whitepiece = BitmapFactory.decodeResource(getResources(), R.drawable.stone_w2);
        blackpiece = BitmapFactory.decodeResource(getResources(), R.drawable.stone_b1);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int width = Math.min(widthSize, heightSize);
        if (widthMode == MeasureSpec.UNSPECIFIED) {
            width = heightSize;
        } else if (heightMode == MeasureSpec.UNSPECIFIED) {
            width = widthSize;
        }
        setMeasuredDimension(width, width);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mPanelWidth = w;
        mLineHeight = mPanelWidth * 1.0f / MAX_LINE;

        int pieceWidth = (int) (mLineHeight * ratioPieceOfLineHeight);
        whitepiece = Bitmap.createScaledBitmap(whitepiece, pieceWidth, pieceWidth, false);
        blackpiece = Bitmap.createScaledBitmap(blackpiece, pieceWidth, pieceWidth, false);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (isGameOver) return false;

        int action = event.getAction();
        if (action == MotionEvent.ACTION_UP) {
            int x = (int) event.getX();
            int y = (int) event.getY();
            Point p = getValidPoint(x, y);
            if (whiteArray.contains(p) || blackArray.contains(p)) {
                return false;
            }
            if (!canGo){
                Toast.makeText(getContext(), "请等待对方走棋后再点击", Toast.LENGTH_SHORT).show();
                return false;
            }
            if (TYPE == 1) {
                addArray1(isWhite, p);
            } else if (TYPE == 2) {
                try {
                    addArray(isWhite, p);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
        return true;
    }

    private void addArray1(boolean isWhite, Point p) {
        if (isWhite) {
            whiteArray.add(p);
        } else {
            blackArray.add(p);
        }
        invalidate();
        Message message = new Message();
        message.what = 1;
        handler.sendMessage(message);
    }

    private void addArray(boolean isWhite, final Point p) throws JSONException {
        if (isWhite) {
            JSONObject jsonObject;
            JSONArray jsonArray;
            if (whiteJson.equals("")) {
                jsonObject = new JSONObject();
                jsonArray = new JSONArray();
                JSONObject job = new JSONObject();
                job.put("x", p.x);
                job.put("y", p.y);
                jsonArray.put(job);
                jsonObject.put("whiteJson", jsonArray);
                whiteJson = jsonObject.toString();
                GoBang goBang = new GoBang();
                goBang.setWhite(whiteJson);
                goBang.update(objID, new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            whiteArray.add(p);
                            invalidate();
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    }
                });
            } else {
                jsonObject = new JSONObject(whiteJson);
                jsonArray = jsonObject.getJSONArray("whiteJson");
                JSONObject job = new JSONObject();
                job.put("x", p.x);
                job.put("y", p.y);
                jsonArray.put(job);
                jsonObject.put("whiteJson", jsonArray);
                whiteJson = jsonObject.toString();
                GoBang goBang = new GoBang();
                goBang.setWhite(whiteJson);
                goBang.update(objID, new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            whiteArray.add(p);
                            invalidate();
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    }
                });
            }
        } else {
            JSONObject jsonObject;
            JSONArray jsonArray;
            if (blackJson.equals("")) {
                jsonObject = new JSONObject();
                jsonArray = new JSONArray();
                JSONObject job = new JSONObject();
                job.put("x", p.x);
                job.put("y", p.y);
                jsonArray.put(job);
                jsonObject.put("blackJson", jsonArray);
                blackJson = jsonObject.toString();
                GoBang goBang = new GoBang();
                goBang.setBlack(blackJson);
                goBang.update(objID, new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        blackArray.add(p);
                        invalidate();
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                });
            } else {
                jsonObject = new JSONObject(blackJson);
                jsonArray = jsonObject.getJSONArray("blackJson");
                JSONObject job = new JSONObject();
                job.put("x", p.x);
                job.put("y", p.y);
                jsonArray.put(job);
                jsonObject.put("blackJson", jsonArray);
                blackJson = jsonObject.toString();
                GoBang goBang = new GoBang();
                goBang.setBlack(blackJson);
                goBang.update(objID, new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        blackArray.add(p);
                        invalidate();
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                });
            }
        }
    }

    private Point getValidPoint(int x, int y) {
        return new Point((int) (x / mLineHeight), (int) (y / mLineHeight));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBoard(canvas);
        drawPieces(canvas);
        checkGameOver();
    }

    private void checkGameOver() {
        boolean whiteWin = checkFiveInLine(whiteArray);
        boolean blackWin = checkFiveInLine(blackArray);
        if (whiteWin || blackWin) {
            isGameOver = true;
            isWhiteWinner = whiteWin;
            String text = isWhiteWinner ? "白棋胜利" : "黑棋胜利";
            Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
        }
    }

    private boolean checkFiveInLine(List<Point> points) {
        for (Point p : points) {
            int x = p.x;
            int y = p.y;

            boolean win = checkHorizontal(x, y, points);
            if (win) return true;
            win = checkVertical(x, y, points);
            if (win) return true;
            win = checkLeftDiagonal(x, y, points);
            if (win) return true;
            win = checkRightDiagonal(x, y, points);
            if (win) return true;
        }
        return false;
    }

    private boolean checkHorizontal(int x, int y, List<Point> points) {
        int count = 1;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x - i, y))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x + i, y))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;
        return false;
    }

    private boolean checkVertical(int x, int y, List<Point> points) {
        int count = 1;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x, y - i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x, y + i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;
        return false;
    }

    private boolean checkLeftDiagonal(int x, int y, List<Point> points) {
        int count = 1;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x - i, y + i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x + i, y - i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;
        return false;
    }

    private boolean checkRightDiagonal(int x, int y, List<Point> points) {
        int count = 1;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x - i, y - i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x + i, y + i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;
        return false;
    }

    private void drawPieces(Canvas canvas) {
        for (int i = 0, n = whiteArray.size(); i < n; i++) {
            Point whitePoint = whiteArray.get(i);
            canvas.drawBitmap(whitepiece,
                    (whitePoint.x + (1 - ratioPieceOfLineHeight) / 2) * mLineHeight,
                    (whitePoint.y + (1 - ratioPieceOfLineHeight) / 2) * mLineHeight, null);
        }
        for (int i = 0, n = blackArray.size(); i < n; i++) {
            Point blackPoint = blackArray.get(i);
            canvas.drawBitmap(blackpiece,
                    (blackPoint.x + (1 - ratioPieceOfLineHeight) / 2) * mLineHeight,
                    (blackPoint.y + (1 - ratioPieceOfLineHeight) / 2) * mLineHeight, null);
        }
    }

    public void reStart() {
        whiteArray.clear();
        blackArray.clear();
        isGameOver = false;
        isWhiteWinner = false;
        invalidate();
    }

    private void drawBoard(Canvas canvas) {
        int w = mPanelWidth;
        float lineHeight = mLineHeight;

        for (int i = 0; i < 10; i++) {
            int startX = (int) (lineHeight / 2);
            int endX = (int) (w - lineHeight / 2);
            int y = (int) ((0.5 + i) * lineHeight);
            canvas.drawLine(startX, y, endX, y, paint);
            canvas.drawLine(y, startX, y, endX, paint);
        }
    }

    @Nullable
    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE, super.onSaveInstanceState());
        bundle.putBoolean(INSTANCE_GAME_OVER, isGameOver);
        bundle.putParcelableArrayList(INSTANCE_WHITE_ARRAY, whiteArray);
        bundle.putParcelableArrayList(INSTANCE_BLACK_ARRAY, blackArray);
        return bundle;
    }

    public void setTYPE(int TYPE) {
        this.TYPE = TYPE;
    }

    public void setObjID(String id) {
        this.objID = id;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            isGameOver = bundle.getBoolean(INSTANCE_GAME_OVER);
            whiteArray = bundle.getParcelableArrayList(INSTANCE_WHITE_ARRAY);
            blackArray = bundle.getParcelableArrayList(INSTANCE_BLACK_ARRAY);
            super.onRestoreInstanceState(bundle.getParcelable(INSTANCE));
            return;
        }
        super.onRestoreInstanceState(state);
    }
}
